﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Common.Rh;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;
using System.IO;

namespace RH
{
   public partial class wfProcPlaRegMnt : EditPage
   {
      public const int _GRDLIST_STANULADO = 9;

      protected void Page_Load(object sender, EventArgs e)
      {
         if (this.IsPostBack)
         {
            this.LoadInPostBack();
            return;
         }
         this.LoadData();
      }
      public override void LoadInPostBack()
      {
         this.RegisterGeneralScripts();
      }
      public override void LoadInitialSettings()
      {
         this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
         this.SetInitialTitle("Proceso Planilla Regularizaciones");
      }
      public override void DataToControls()
      {

         EProcPlani objEA = new EProcPlani();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.ProcPlani));
         objEA.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
         objEA.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objEA.IdMes = Request.QueryString["IdMes"];
         objEA.IdForPago = Request.QueryString["idForPago"];
         objEA.IdPlanilla = Request.QueryString["IdPlanilla"];

         if (Request.QueryString["NuProcAnual"] != null)

            objEA.NuProcAnual = Convert.ToInt16(Request.QueryString["NuProcAnual"]);

         this.txtNroProcAnual.Text = Request.QueryString["NuProcAnual"];
         objEA = (EProcPlani)objBO.GetByKey(objEA);

         if (objEA != null)
         {
            WebHelper.EntityToControl(objEA, "IdPlanilla", txtidPlanilla);

            EPlanilla objEPla = new EPlanilla();
            IBOQuery objBOPla = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Planilla));
            objEPla.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEPla.IdPlanilla = Request.QueryString["IdPlanilla"];
            objEPla = (EPlanilla)objBOPla.GetByKey(objEPla);
            if (objEPla != null)
               WebHelper.EntityToControl(objEPla, "DsPlanilla", txtdsPlanilla);

         }

         MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
         ETablaGenDet objEDet = new ETablaGenDet();
         objEDet.IdTabla = ConstMultitabla.FORMA_PAGO;
         objEDet.IdCodigo = Request.QueryString["idForPago"];
         objEDet = (ETablaGenDet)objBOI.GetDetailByKey(objEDet);

         if (objEDet != null)
            WebHelper.EntityToControl(objEDet, "DsDescrip", txtdsFormaPago);



         EProcPlaReg objEB = new EProcPlaReg();

         RHBOQry.ProcPlaReg objBOPerC = (RHBOQry.ProcPlaReg)WCFHelper.GetObject<RHBOQry.ProcPlaReg>(typeof(RHBOQry.ProcPlaReg));

         objEB.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
         objEB.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objEB.IdForPago = Request.QueryString["IdForPago"];
         objEB.IdPlanilla = Request.QueryString["IdPlanilla"];
         objEB.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"].ToString());
         objEB.IdTipRegula = ConstTipoRegularizacion.REGULARIZACION;

         DataTable dt = objBOPerC.GetByParentKey(objEB);

         this.GridSetDataBinding(grdList, dt);

         }
      public void RegisterEditPopupScripts()
      {
         StringBuilder sbA = new StringBuilder();

         sbA.AppendLine("var varRet = modalDialog('../RH/wfConcepRemu.aspx',725,400);");
         sbA.AppendLine("if(varRet==null)");
         sbA.AppendLine("return false;");
         sbA.AppendLine("ctl = document.getElementById('" + this.hdnidConRemu.ClientID + "');");
         sbA.AppendLine("ctl.value = varRet[0];");
         sbA.AppendLine("ctl = document.getElementById('" + this.txtidConRemu.ClientID + "');");
         sbA.AppendLine("ctl.value = varRet[1];");
         sbA.AppendLine("return false;");
         this.txtidConRemu.OnClientClick = sbA.ToString();

         StringBuilder sbB = new StringBuilder();

         sbB.AppendLine("var varRet = modalDialog('../RH/wfPersonalPlani.aspx?IdPlanilla=" + Request.QueryString["IdPlanilla"] + "'" + ",725,400);");
         sbB.AppendLine("if(varRet==null)");
         sbB.AppendLine("return false;");
         sbB.AppendLine("ctl = document.getElementById('" + this.hdnidPersonal.ClientID + "');");
         sbB.AppendLine("ctl.value = varRet[0];");
         sbB.AppendLine("ctl = document.getElementById('" + this.txtidPersonal.ClientID + "');");
         sbB.AppendLine("ctl.value = varRet[1];");
         sbB.AppendLine("return false;");
         this.txtidPersonal.OnClientClick = sbB.ToString();

         StringBuilder sb = new StringBuilder();
         sb.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
         //sb.AppendLine("debugger;");
         //if (this.GridEditAction == GridEditAction.AddNew)
         //{
         //    sb.AppendLine("varRpta = gridFindCellValueInRow('" + grdList.ClientID + "',new Array('" + _GRDLIST_IDCONREMU + "'), new Array(document.getElementById('" + this.hdnidConRemu.ClientID + "').value),'Ya existe el concepto de Remuneracion');");
         //    sb.AppendLine("if(varRpta==true)");
         //    sb.AppendLine("return !varRpta;");
         //}

         //sb.AppendLine("varRpta = isEmptyControl('" + this.txtnuSecuen.ClientID + "','Ingrese Numero de Secuencia.');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         sb.AppendLine("return true;}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb.ToString(), true);
         ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sbA.ToString(), true);
         ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sbB.ToString(), true);

         this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
         this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";

      }
      protected void bttOkPopup_Click(object sender, EventArgs e)
      {

         DataTable dt = (DataTable)this.DataSource;
         DataRow dr = null;

         if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
         {
            dr = dt.NewRow();
         }
         else
         {
            dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
         }

         if (this.GridEditAction != GridEditAction.Delete)
         {
            dr["idPeriodo"] = Session[ConstSessionVar.PERIODO].ToString();
            dr["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
            dr["IdForPago"] = Request.QueryString["IdForPago"].ToString();
            dr["IdPlanilla"] = Request.QueryString["IdPlanilla"].ToString();
            dr["nuProcAnual"] = Request.QueryString["NuProcAnual"].ToString();
            dr["idPersonal"] = this.hdnidPersonal.Value.ToString();
            dr["dsPersonal"] = this.txtidPersonal.Text.ToString();
            dr["idConRemu"] = this.hdnidConRemu.Value.ToString();
            dr["dsConRemu"] = this.txtidConRemu.Text.ToString();
            dr["IdTipRegula"] = ConstTipoRegularizacion.REGULARIZACION;
            dr["nuHoras"] = this.txtnuHoras.Text.ToString();
            dr["mtRegulaMn"] = this.txtmtRegulaMn.Text.ToString();
            dr["mtRegulaMe"] = this.txtmtRegulaMe.Text.ToString();
            dr["dsObserva"] = this.txtdsObserva.Text.ToString();
            dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;

         }
         else
         {
            dr["stAnulado"] = ConstFlagEstado.ACTIVADO;
         }

         if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
         {
            dt.Rows.Add(dr);
         }


         this.GridSetDataBinding(grdList, dt);
      }
      protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_NEW:
               this.GridEditAction = GridEditAction.AddNew;
               this.lblTitlePopup.Text = "Proceso Planilla Reg (Nuevo)";
               this.mdlPopup.Show();
               this.LoadDataEditPopup(grdList, -1);
               this.RegisterEditPopupScripts();
               break;
            case ConstGridRowCommand.GRIDDELETE:
               this.lblTitlePopup.Text = "Proceso Planilla Reg (Dar de Baja)";
               this.GridEditAction = GridEditAction.Delete;
               this.mdlPopup.Show();
               this.LoadDataEditPopup(grdList, this.EditRowIndex);
               this.RegisterEditPopupScripts();
               break;
         }

      }
      protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
              String strRI = e.Row.RowIndex.ToString();

              ImageButton bttedit = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDEDIT);
              ImageButton bttdelete = (ImageButton)e.Row.FindControl("grdBtt" + ConstGridRowCommand.GRIDDELETE);

              bttedit.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDEDIT + "','" + strRI + "');";
              bttdelete.OnClientClick = "javascript:return validateGridCommands('" + ConstGridRowCommand.GRIDDELETE + "','" + strRI + "');";

              if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
              {
                  e.Row.ForeColor = System.Drawing.Color.Red;
                  bttedit.ImageUrl = "../Images/Icons/Disabled/Edit.png";
                  bttdelete.ImageUrl = "../Images/Icons/Disabled/Delete.png";
              }
              else
              {
                  if (Request.QueryString["StProceso"] == ConstEstadoProcePlani.CERRADA)
                  {
                      e.Row.ForeColor = System.Drawing.Color.Blue;
                      bttedit.ImageUrl = "../Images/Icons/Disabled/Edit.png";
                      bttdelete.ImageUrl = "../Images/Icons/Disabled/Delete.png";
                  }
              }
          }
      }
      public override void LoadDataEditPopup(GridView grid, int rowIndex)
      {
         this.ClearEditPopup();
         this.LockControlsPopup();

         DataRow dr = this.GridGetRowFromDataKey(this.DataSource, grdList, rowIndex);

         if (dr == null)
            return;
      
         WebHelper.RowToControl(dr, "idPersonal", hdnidPersonal);
         WebHelper.RowToControl(dr, "dsPersonal", txtidPersonal);
         WebHelper.RowToControl(dr, "idConRemu", hdnidConRemu);
         WebHelper.RowToControl(dr, "dsConRemu", txtidConRemu);
         WebHelper.RowToControl(dr, "nuHoras", txtnuHoras);
         WebHelper.RowToControl(dr, "mtRegulaMn", txtmtRegulaMn);
         WebHelper.RowToControl(dr, "mtRegulaMe", txtmtRegulaMe);
         WebHelper.RowToControl(dr, "dsObserva", txtdsObserva);

      }
      public override void ClearEditPopup()
      {
          this.txtidPersonal.Text = "";
          this.txtidConRemu.Text = "";
          this.txtnuHoras.Text = "";
          this.txtmtRegulaMn.Text = "";
          this.txtmtRegulaMe.Text = "";
          this.txtdsObserva.Text = "";
      }
      public void LockControlsPopup()
      {
          switch (this.GridEditAction)
          {
              case GridEditAction.AddNew:
                  this.txtidPersonal.EnabledButton = true;
                  this.txtidConRemu.EnabledButton = true;
                  this.txtnuHoras.Enabled = true;
                  this.txtmtRegulaMn.Enabled = true;
                  this.txtmtRegulaMe.Enabled = true;
                  this.txtdsObserva.Enabled = true;
                  break;
              case GridEditAction.Edit:
                  this.txtidPersonal.EnabledButton = false;
                  this.txtidConRemu.EnabledButton = false;
                  break;
              case GridEditAction.Delete:
                  this.txtidPersonal.EnabledButton = false;
                  this.txtidConRemu.EnabledButton = false;
                  this.txtnuHoras.Enabled = false;
                  this.txtmtRegulaMn.Enabled = false;
                  this.txtmtRegulaMe.Enabled = false;
                  this.txtdsObserva.Enabled = false;
                  break;
          }
      }
      public override void LockControls()
      {
          if (Request.QueryString["StProceso"] == ConstEstadoProcePlani.CERRADA)
              this.mnuGrid.Enabled = false;
      }


      protected void grdList_RowCommand(Object sender, GridViewCommandEventArgs e)
      {
         this.EditRowIndex = Convert.ToInt32(e.CommandArgument);

         switch (e.CommandName)
         {
            case ConstGridRowCommand.GRIDEDIT:
               this.lblTitlePopup.Text = "(Editar)";
               this.GridEditAction = GridEditAction.Edit;
               this.mdlPopup.Show();
               this.LoadDataEditPopup(grdList, this.EditRowIndex);
               this.RegisterEditPopupScripts();
               break;
            case ConstGridRowCommand.GRIDDELETE:
               this.lblTitlePopup.Text = "(Eliminar)";
               this.GridEditAction = GridEditAction.Delete;
               this.mdlPopup.Show();
               this.LoadDataEditPopup(grdList, this.EditRowIndex);
               this.RegisterEditPopupScripts();
               break;
         }
      }
      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_SAVE:
            case ConstMenuToolbarValue.BUTTON_SAVENEW:
               if (this.FormEditAction != FormEditAction.Delete)
                  this.SaveData(e.Item.Value);
               else
                  this.DeleteData();
               break;

            case ConstMenuToolbarValue.BUTTON_EXIT:
               this.Response.Redirect("wfProcPlaRegBnd.aspx");
               break;
         }

      }
      public override void SaveData(String key)
      {
         if (this.ValidateData() == false)
            return;

         IEntityBase objE = (IEntityBase)this.CreateEntitySet();

         IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.ProcPlaReg));

         String[] strRet = objPro.UpdateData(objE);
         String strMsg = "";

         switch (this.FormEditAction)
         {

            case FormEditAction.AddNew:
            case FormEditAction.Copy:
               strMsg = "Se ha registrado la Planilla : " + strRet[0].ToString();
               break;
            default:
               strMsg = "Se ha modificado la Planilla No.: "+ txtNroProcAnual.Text +' '+txtdsPlanilla.Text;
               break;
         }
         this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, strMsg, "wfProcPlaRegBnd.aspx");

      }
      public override void RegisterGeneralScripts()
      {
         txtidPlanilla.Attributes.Add("readonly", "true");
         txtdsFormaPago.Attributes.Add("readonly", "true");
         txtdsPlanilla.Attributes.Add("readonly", "true");
         txtNroProcAnual.Attributes.Add("readonly", "true");

         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validateEditForm(key){");

         //sb.AppendLine("var varRpta = isEmptyControl('" + this.txtdsPlanilla.ClientID + "','Ingrese Descripcion Planilla');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");
         //sb.AppendLine("var varRpta = isEmptyControl('" + this.txtnuProcAnual.ClientID + "','Ingrese Numero de Proceso Anual');");
         //sb.AppendLine("if(varRpta==true)");
         //sb.AppendLine("return !varRpta;");

         sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
         sb.AppendLine("}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
      }
      public override Object CreateEntitySet()
      {

         DataTable dt = (DataTable)this.DataSource;
         this.ClearDeletedRow(this.DataSource, "stAnulado");
         IList<EProcPlaReg> colECerti = new List<EProcPlaReg>();

         if (this.FormEditAction == FormEditAction.Delete)
         {
            foreach (DataRow dr in dt.Rows)
            {
               this.MarkDeletedRow(dr, "stAnulado");
            }
         }


         for (int intTypeUpd = 0; intTypeUpd <= 1; intTypeUpd++)
         {
            DataTable dtChange = null;
            if (intTypeUpd == 0)
               dtChange = dt.GetChanges(DataRowState.Added);
            else
               dtChange = dt.GetChanges(DataRowState.Modified);


            if (dtChange != null)
            {
               foreach (DataRow drDet in dtChange.Rows)
               {
                  EProcPlaReg objEDet = DataHelper.CopyDataRowToEntity<EProcPlaReg>(drDet, typeof(EProcPlaReg));

                  if (drDet.RowState == DataRowState.Added)
                     objEDet.EntityState = EntityState.Added;

                  if (drDet.RowState == DataRowState.Modified)
                  {
                     if (objEDet.StAnulado == ConstFlagEstado.DESACTIVADO)
                        objEDet.EntityState = EntityState.Modified;
                     else
                        objEDet.EntityState = EntityState.Deleted;
                  }

                  colECerti.Add(objEDet);
               }
            }
         }

         EProcPlaRegSet objESet = new EProcPlaRegSet();
         objESet.EProcPlaReg = colECerti;

         return objESet;
      }
      public override void DeleteData()
      {
         IEntityBase objE = (IEntityBase)this.CreateEntitySet();
         IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.ProcPlaReg));
         objPro.DeleteData(objE);

         this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "Se anulola Planilla Regularicion  : " + txtidPlanilla.Text, "wfPerDereHabiBnd.aspx");

      }
      }
}